package com.ruoyi.project.websiteContent.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.v2.uid.UidUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.online_experiment.domain.OnlineExperiment;
import com.ruoyi.project.online_experiment.mapper.OnlineExperimentMapper;
import com.ruoyi.project.websiteContent.domain.WebsiteContent;
import com.ruoyi.project.websiteContent.service.IWebsiteContentService;
import com.ruoyi.project.websiteContentTitle.domain.WebsiteTitle;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 新闻具体内容Controller
 * 
 * @author lvyongwei
 * @date 2020-07-23
 */
@Controller
@RequestMapping("/system/content")
public class WebsiteContentController extends BaseController
{
    private String prefix = "system/websiteContent";

    @Autowired
    private IWebsiteContentService websiteContentService;

    @Autowired
    private OnlineExperimentMapper onlineExperimentMapper;

    @RequiresPermissions("system:content:view")
    @GetMapping()
    public String content()
    {
        return prefix + "/content";
    }

    /**
     * 查询新闻具体内容列表
     */
    @RequiresPermissions("system:content:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WebsiteContent websiteContent)
    {
        startPage();
        List<WebsiteContent> list = websiteContentService.selectWebsiteContentList(websiteContent);
        return getDataTable(list);
    }

    /**
     * 导出新闻具体内容列表
     */
    @RequiresPermissions("system:content:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WebsiteContent websiteContent)
    {
        List<WebsiteContent> list = websiteContentService.selectWebsiteContentList(websiteContent);
        ExcelUtil<WebsiteContent> util = new ExcelUtil<WebsiteContent>(WebsiteContent.class);
        return util.exportExcel(list, "content");
    }

    /**
     * 新增新闻具体内容
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存新闻具体内容
     */
    @RequiresPermissions("system:content:add")
    @Log(title = "新闻具体内容", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WebsiteContent websiteContent, MultipartFile[] file) throws IOException {
        String accessorys = "";
        if(StringUtils.isEmpty(file) || file.length == 0){
            websiteContent.setAccessorys(null);
        }else{
            try{
                for(MultipartFile file1:file){
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
                    // 上传并返回新文件名称
                    String fileName = FileUploadUtils.upload(filePath, file1);
                    accessorys += file1.getOriginalFilename() + ":" +fileName + ";";
                }
                websiteContent.setAccessorys(accessorys);
            }catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
        }
        /**
         * 创建内容对象
         */
        WebsiteContent websiteContent1 = new WebsiteContent();
        websiteContent1.setWebsiteId(websiteContent.getWebsiteId());
        /**
         * 查询已经存在的内容
         */
        List<WebsiteContent> websiteContents=websiteContentService.selectWebsiteContentList(websiteContent1);
        /**
         * 开关
         */
        boolean flag=false;
        for(WebsiteContent content:websiteContents){
            /**
             * 判断如果名称为空则跳过     (可能会有无列表项修改为有列表项，此时需要做此判断)
             */
            if(content.getContentName() == null || StringUtils.isEmpty(content.getContentName())){
                /**
                 * 随机给生成一个标题
                 */
                content.setContentName("标题"+ UUID.randomUUID().toString().substring(0,new Random().nextInt(16)) );
                websiteContentService.updateWebsiteContent(content);
                continue;
            }
            /**
             * 判断如果列表项名称重复
             */
            if(content.getContentName().equals(websiteContent.getContentName())){
                flag = true;
            }
        }
        if(flag==true){
            return AjaxResult.error("列表标题重复");
        }
        return toAjax(websiteContentService.insertWebsiteContent(websiteContent));
    }

    /**
     * 修改新闻具体内容
     */
    @GetMapping("/edit/{contentId}")
    public String edit(@PathVariable("contentId") Long contentId, ModelMap mmap)
    {
        WebsiteContent websiteContent = websiteContentService.selectWebsiteContentById(contentId);
        mmap.put("websiteContent", websiteContent);
        return prefix + "/edit";
    }

    /**
     * 修改保存新闻具体内容
     */
    @RequiresPermissions("system:content:edit")
    @Log(title = "新闻具体内容", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WebsiteContent websiteContent,MultipartFile[] file) throws IOException {
        System.err.println(websiteContent.getCreateTime());
        String accessorys = "";
        if(StringUtils.isEmpty(file) || file.length == 0){
            websiteContent.setAccessorys(null);
        }else{
            try{
                for(MultipartFile file1:file){
                    // 上传文件路径
                    String filePath = RuoYiConfig.getUploadPath();
                    // 上传并返回新文件名称
                    String fileName = FileUploadUtils.upload(filePath, file1);
                    accessorys += file1.getOriginalFilename() + ":" +fileName + ";";
                }
                websiteContent.setAccessorys(accessorys);
            }catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
        }
        return toAjax(websiteContentService.updateWebsiteContent(websiteContent));
    }

    /**
     * 删除新闻具体内容
     */
    @RequiresPermissions("system:content:remove")
    @Log(title = "新闻具体内容", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(websiteContentService.deleteWebsiteContentByIds(ids));
    }


    /**
     * 管理后台查看新闻具体内容
     */
    @GetMapping("/lookContent")
    public String lookContent(Long websiteTitleId, ModelMap mmap)
    {
        WebsiteContent websiteContent = websiteContentService.selectWebsiteContentById(websiteTitleId);
        mmap.put("websiteContent", websiteContent);
        return prefix + "/look";
    }


    /**
     * 获取具体展示的内容
     * @param  isTwoleveltitle 标题实体,根据标题id以及是否有二级标题标识去查找信息
     * @return
     */
    @GetMapping("/getWebSiteContent")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getAllContent(Long websiteTitleId,int isTwoleveltitle,Integer pageNum,Integer pageSize){
        if(isTwoleveltitle!=1 || isTwoleveltitle==2){
            pageNum=1;
            pageSize=1;
        } else{
            if(StringUtils.isEmpty(pageNum) || pageNum==0){
                pageNum=1;
            }
            if(StringUtils.isEmpty(pageSize) || pageSize==0){
                pageSize=10;
            }
        }
        /**
         * 设置查询条件
         */
        WebsiteTitle websiteTitle=new WebsiteTitle();
        websiteTitle.setIsTwoleveltitle((long) isTwoleveltitle);
        websiteTitle.setTitleId(websiteTitleId);
        try{
            /**
             * 执行分页操作
             */
            PageHelper.startPage(pageNum,pageSize);
            /**
             * 执行查询操作
             */
            List<WebsiteContent> websiteContents=websiteContentService.getAllContent(websiteTitle);
            System.out.println(websiteContents);
            PageInfo<WebsiteContent> pageInfo=new PageInfo<WebsiteContent>(websiteContents);
            return AjaxResult.success("查询数据成功",pageInfo);
        }catch (Exception e){
            return AjaxResult.success("查询数据失败");
        }
    }

    /**
     * 获取具体展示的内容
     * @param
     * @return
     */
    @GetMapping("/getAllWebsite")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getAllWebsite(Long websiteTitleId,Integer pageNum,Integer pageSize){
        if(StringUtils.isEmpty(pageNum) || pageNum==0){
                pageNum=1;
        }
        if(StringUtils.isEmpty(pageSize) || pageSize==0){
                pageSize=10;
        }
        /**
         * 设置查询条件
         */
        WebsiteTitle websiteTitle=new WebsiteTitle();
        websiteTitle.setTitleId(websiteTitleId);
        try{
            /**
             * 执行分页操作
             */
            PageHelper.startPage(pageNum,pageSize);
            /**
             * 执行查询操作
             */
            List<WebsiteContent> websiteContents=websiteContentService.getAllWebsite(websiteTitle);
            PageInfo<WebsiteContent> pageInfo=new PageInfo<WebsiteContent>(websiteContents);
            return AjaxResult.success("查询数据成功",pageInfo);
        }catch (Exception e){
            return AjaxResult.success("查询数据失败");
        }
    }

    /**
     * 获取所有开放的实验信息
     * @return
     */
    @GetMapping("/getOpenExperiment")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getOpenOnlineExperiment(){
        List<OnlineExperiment> onlineExperiments=onlineExperimentMapper.getOpenOnlineExperiment();
        if(StringUtils.isEmpty(onlineExperiments) || onlineExperiments.size()==0){
            return AjaxResult.error("没有开放实验");
        }else{
            return AjaxResult.success("获取到开放实验",onlineExperiments);
        }
    }


    /**
     * 根据内容id获取内容详情s
     * @return
     */
    @GetMapping("/getContent")
    @ResponseBody
    @CrossOrigin
    public AjaxResult getContent(Long contentId){
        /**
         * 根据内容id获取内容详情
         */
        WebsiteContent websiteContent = websiteContentService.selectWebsiteContentById(contentId);
        if(StringUtils.isEmpty(websiteContent) || websiteContent==null){
            return AjaxResult.error("没有获取到内容");
        }else{
            return AjaxResult.success("获取到资讯内容",websiteContent);
        }
    }

    /**
     * 附件下载
     * @return
     */
    @GetMapping("/download")
    @CrossOrigin
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + com.ruoyi.common.utils.StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = com.ruoyi.common.utils.StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
}
